package com.genesis.yunnanji.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.genesis.yunnanji.R;
import com.genesis.yunnanji.adapter.CollectAdapter;
import com.genesis.yunnanji.bean.CollectBean;
import com.genesis.yunnanji.config.GenesisApiConfig;
import com.genesis.yunnanji.utils.NetWorkUtils;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.json.JSONObject;
import org.xutils.http.RequestParams;

import java.util.ArrayList;
import java.util.List;



public class MyCollect extends BaseActivity {
    private static final int MYLIVE_MODE_CHECK = 0;
    private static final int MYLIVE_MODE_EDIT = 1;

    private RecyclerView mRecyclerview;
    private SmartRefreshLayout refreshLayout;
    private Button mBtnDelete;
    private ImageView mSelectAll;
    private TextView mBtnEditor;
    private CollectAdapter collectAdapter = null;
    private List<CollectBean.ResultBean.ListBean> mList = new ArrayList<>();
    private int mEditMode = MYLIVE_MODE_CHECK;
    private boolean isSelectAll = false;
    private boolean editorStatus = false;
    private int index = 0;
    private Toolbar mToolbar;
    private CollectBean collectBean;
    private int page = 1;
    private Intent intent;
    private RelativeLayout bottomView;
    private LinearLayout llSelectAll;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_mycollect);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mRecyclerview = (RecyclerView) findViewById(R.id.rv_mycollect_rv);
        mToolbar = (Toolbar) findViewById(R.id.tb_mycollect_toolbar);
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.srl_mycollect_fresh);
        mBtnDelete = (Button) findViewById(R.id.bt_mycollect_cancel);
        mSelectAll = (ImageView) findViewById(R.id.iv_mycollect_collect);
        mBtnEditor = (TextView) findViewById(R.id.tv_mycollect_edit);
        bottomView = (RelativeLayout) findViewById(R.id.rl_mycollect_bottom);
        llSelectAll = (LinearLayout) findViewById(R.id.rl_mycollect_selectall);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.main_color), 20);
        bottomView.setVisibility(View.GONE);
        getData(refreshLayout);
    }


    @Override
    protected void setUpView() {
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mBtnEditor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                updataEditMode();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page += 1;
                getData(refreshLayout);
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mList.removeAll(mList);
                getData(refreshLayout);
            }
        });

        llSelectAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectAllMain();
            }
        });

        mBtnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<Integer> ids = new ArrayList<Integer>();
                for (int i = mList.size(), j = 0; i > j; i--) {
                    CollectBean.ResultBean.ListBean collectBean = mList.get(i - 1);
                    if (collectBean.isSelect()) {
                        ids.add(collectBean.getId());
                        mList.remove(collectBean);
                        index--;
                    }
                }
                index = 0;
                setBtnBackground(index);
                if (mList.size() == 0) {
                    bottomView.setVisibility(View.GONE);
                }
                getDelete(ids);
                collectAdapter.notifyDataSetChanged();
            }
        });
    }


    private void setBtnBackground(int size) {
        if (size != 0) {
            mBtnDelete.setEnabled(true);
        } else {
            mBtnDelete.setEnabled(false);
        }
    }


    private void updataEditMode() {
        mEditMode = mEditMode == MYLIVE_MODE_CHECK ? MYLIVE_MODE_EDIT : MYLIVE_MODE_CHECK;
        if (mEditMode == MYLIVE_MODE_EDIT) {
            editorStatus = true;
            mBtnEditor.setText("完成");
            bottomView.setVisibility(View.VISIBLE);
            refreshLayout.setEnableRefresh(false);
        } else {
            refreshLayout.setEnableRefresh(true);
            mBtnEditor.setText("编辑");
            bottomView.setVisibility(View.GONE);
            editorStatus = false;
            clearAll();
        }
        collectAdapter.setEditMode(mEditMode);
    }

    private void clearAll() {
        isSelectAll = false;
        setBtnBackground(0);
    }


    private void getData(final RefreshLayout refreshLayout) {
        final RequestParams params = new RequestParams(GenesisApiConfig.HOST + GenesisApiConfig.COLLECT);
        params.addBodyParameter("__apptoken__", genesisUtils.getAppToken());
        params.addBodyParameter("p", page + "");
        NetWorkUtils.doCacheGet(params, new NetWorkUtils.HttpResultListener() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                Log.e("mdata", jsonObject.toString());
                Gson gson = new Gson();
                collectBean = gson.fromJson(jsonObject.toString(), CollectBean.class);

                if (page == 1) {
                    mList = collectBean.getResult().getList();
                    collectAdapter = new CollectAdapter(mList, context);
                    mRecyclerview.setLayoutManager(new LinearLayoutManager(context));
                    mRecyclerview.addItemDecoration(new HorizontalDividerItemDecoration.Builder(context).color(getResources().getColor(R.color.divider)).build());
                    mRecyclerview.setAdapter(collectAdapter);
                    collectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                            if (mEditMode == MYLIVE_MODE_CHECK) {
                                intent = new Intent(context, WebActivity.class);
                                intent.putExtra("url", mList.get(position).getTaget_link());
                                startActivity(intent);
                            } else {
                                if (editorStatus) {
                                    CollectBean.ResultBean.ListBean myLive = mList.get(position);
                                    boolean isSelect = myLive.isSelect();
                                    if (!isSelect) {
                                        index++;
                                        myLive.setSelect(true);
                                        if (index == mList.size()) {
                                            isSelectAll = true;
                                            mSelectAll.setBackgroundResource(R.mipmap.check);
                                        }

                                    } else {
                                        myLive.setSelect(false);
                                        index--;
                                        isSelectAll = false;
                                        mSelectAll.setBackgroundResource(R.mipmap.uncheck);
                                    }
                                    setBtnBackground(index);
                                    collectAdapter.notifyDataSetChanged();
                                }
                            }
                        }
                    });
                } else {
                    mList.addAll(collectBean.getResult().getList());
                    collectAdapter.notifyDataSetChanged();
                }


            }

            @Override
            public void OnCached(JSONObject jsonObject) {
            }

            @Override
            public void onFinished() {
                if (refreshLayout != null) {
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                }
            }

            @Override
            public void onError(String errorStr) {

            }
        });
    }

    private void getDelete(ArrayList<Integer> map) {
        final RequestParams params = new RequestParams(GenesisApiConfig.HOST + GenesisApiConfig.DELETE_COLLECT);
        params.addBodyParameter("__apptoken__", genesisUtils.getAppToken());
        params.addParameter("id[]", map);
        Log.e("delete", map.toString());
        NetWorkUtils.doCachePost(params, new NetWorkUtils.HttpResultListener() {
            @Override
            public void onSuccess(JSONObject jsonObject) {

            }
            @Override
            public void OnCached(JSONObject jsonObject) {
            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onError(String errorStr) {

            }
        });
    }

    /**
     * 全选和反选
     */
    private void selectAllMain() {
        if (collectAdapter == null) return;
        if (!isSelectAll) {
            for (int i = 0, j = mList.size(); i < j; i++) {
                mList.get(i).setSelect(true);
            }
            index = mList.size();
            mBtnDelete.setEnabled(true);
            mSelectAll.setBackgroundResource(R.mipmap.check);
            isSelectAll = true;
        } else {
            for (int i = 0, j = mList.size(); i < j; i++) {
                mList.get(i).setSelect(false);
            }
            index = 0;
            mBtnDelete.setEnabled(false);
            isSelectAll = false;
            mSelectAll.setBackgroundResource(R.mipmap.uncheck);
        }
        collectAdapter.notifyDataSetChanged();
        setBtnBackground(index);
    }


}
